from pymongo import MongoClient
import datetime
client = MongoClient("mongodb://root:123456@172.16.21.70:27017/?authSource=admin")
db = client["aiapp"]

    
def init_db(app):
    with app.app_context():
        condition = {'username': "root"}
        count = db.users.count_documents(condition)
        if (count==0):
            current_datetime = datetime.datetime.now()
            document = {"username": "root", "password": "123456", "email": "test@163.com","telephone":"13810001000","timestamp":current_datetime}
            db.users.insert_one(document)
            
def test():
    collection = db["users"]
    
    # 统计整个集合中的文档数量
    count = collection.count_documents({})
    print("集合中的文档数量：", count)

    # 根据条件统计文档数量
    condition = {'age': {'$gt': 18}}
    count = collection.count_documents(condition)

    # document = {"name": "John", "age": 30, "city": "New York"}
    # collection.insert_one(document)

    # document = {"name": "Mars", "age": 21, "city": "China","gender":1}
    # collection.insert_one(document)

    # document = {"name": "Liutao", "age": 15, "city": "China","gender":1}
    # db.users.insert_one(document)
    # db.devices.insert_one(document)
    
    # 插入多个文档
    documents = [
        {"name": "Anna", "age": 25, "city": "London"},
        {"name": "Mike", "age": 32, "city": "San Francisco"}
    ]
    collection.insert_many(documents)

    # 查询单个文档
    result = collection.find_one({"name": "John"})
    print(result)

    # 查询多个文档
    results = collection.find({"city": "New York"})
    for doc in results:
        print(doc)

    # 更新单个文档
    collection.update_one({"name": "John"}, {"$set": {"age": 31}})

    # 更新多个文档
    collection.update_many({"city": "New York"}, {"$set": {"city": "Los Angeles"}})

    # 删除单个文档
    collection.delete_one({"name": "John"})

    # 删除多个文档
    collection.delete_many({"city": "Los Angeles"})

    # 创建单字段索引
    collection.create_index("name")

    # 创建复合索引
    collection.create_index([("name", 1), ("age", -1)])

    # 查询索引信息
    indexes = collection.index_information()

